package edu.nuist.unit01;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wangzhuangzhuang
 * @DESC:
 * @date 2022-04-19 23:06
 */
public class SafeCountBaseCasAndUnsafeCountDemo {
	private AtomicInteger atomicI = new AtomicInteger(0);
	private int i = 0;

	public static void main(String[] args) {

	}

	/**
	 * 使用CAS实现线程安全计数器
	 */
	private void safeCount() {
		for (; ; ) {
			int i = atomicI.get();
			boolean suc = atomicI.compareAndSet(i, ++i);
			if (suc) {
				break;
			}
		}
	}

	/**
	 * 非线程安全计数器
	 */
	private void count() {
		i++;
	}
}